from flask import request, Blueprint, send_from_directory
import os

bp = Blueprint('static', __name__, url_prefix='/static')


@bp.route('/picture')
def picture():
    filetype = request.args.get('type')
    filename = request.args.get('filename')
    print("filename", filename)
    try:
        path = 'static\\picture\\' + filetype + '\\'
        file = path + filename
        if os.path.isdir(file):
            return '<h1>文件夹无法下载</h1>'
        else:
            return send_from_directory(path=file, directory=path, filename=filename, as_attachment=True)
    except (ValueError, ArithmeticError):
        print(ValueError)
        print(ArithmeticError)
        return '<h1>该文件不存在或无法下载</h1>'


@bp.route('/mp3')
def mp3():
    oprname = request.args.get('oprname')
    filename = request.args.get('filename')
    try:
        path = 'static\\song\\' + oprname + '\\'
        file = path + filename
        if os.path.isdir(file):
            return '<h1>文件夹无法下载</h1>'
        else:
            return send_from_directory(path=file, directory=path, filename=filename, as_attachment=True)
    except (ValueError, ArithmeticError):
        print(ValueError)
        print(ArithmeticError)
        return '<h1>该文件不存在或无法下载</h1>'
